package com.bgds.sys.data.iXCom29d.protocol.utils;

import com.cisdi.data.common.exception.BusinessException;
import io.netty.buffer.ByteBuf;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: lhp
 * @date: 2019/10/8
 **/
@Component
public class IXComCodecService {
	
	public Map<String, Object> decode(IXComActionParamDTO dto, byte[] data, Charset charset) {
        int sumLen = 0;

        try{
            sumLen = dto.getPropertyList().stream().mapToInt(IXComActionParamDTO.PropertyConfig::getFixedLength).sum();
        } catch (Exception e) {
            throw new BusinessException("ixcom29d解析数据长度失败");
        }

        if (sumLen != data.length) {
            throw new BusinessException("ixcom29d解析长度与数据长度不一致错误, 解析数据长度为: " + data.length + " 配置长度为: " + sumLen);
        }

        Map<String, Object> map = new HashMap<>(20);
        
        ByteBuffer byteBuffer = ByteBuffer.wrap(data);
    	dto.getPropertyList().forEach(property -> {
    		if (property != null) {
    			Object object = IXComConverterUtils.convertProperty(property, byteBuffer, charset);
    			if (object != null) {
    				map.put(property.getPropertyId(), object);
    			}
    		}
    		
    	});

        return map;
	}

    public List<IXComActionParamDTO.PropertyConfig> decode1(IXComActionParamDTO dto, byte[] data, Charset charset) {
        int sumLen = 0;
        try{
            sumLen = dto.getPropertyList().stream().mapToInt(IXComActionParamDTO.PropertyConfig::getFixedLength).sum();
        } catch (Exception e) {
            throw new BusinessException("ixcom29d解析数据长度失败");
        }
        if (sumLen != data.length) {
            throw new BusinessException("ixcom29d解析长度与数据长度不一致错误, 解析数据长度为: " + data.length + " 配置长度为: " + sumLen);
        }
        ByteBuffer byteBuffer = ByteBuffer.wrap(data);
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
        dto.getPropertyList().forEach(property -> {

            if (property != null) {
                Object value = IXComConverterUtils.convertProperty(property,byteBuffer, charset);
                if (value != null) {
                    property.setValue(value);
                }
            }

        });

        return dto.getPropertyList();
    }



}
